package dk.eclipse.android.helpers;

import android.R;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.SmsManager;
import android.widget.ProgressBar;
import android.widget.Toast;

/**
 * This class is used to listen for SMS SENT broadcasts.
 * 
 * @author Ronni Kahalani
 *
 */
public class SMSSentBroadcastReciever extends BroadcastReceiver{
	private static final String MSG_SMS_SENT_OK = "SMS sent to %s\n%s";
	private static final String MSG_SMS_SENT_RESULT_ERROR_GENERIC_FAILURE = "SMS Generic failure while sending to: %s";
	private static final String MSG_SMS_SENT_RESULT_ERROR_NO_SERVICE = "SMS No service while sending to: %s";
	private static final String MSG_SMS_SENT_RESULT_ERROR_NULL_PDU = "SMS No PDU provided while sending to: %s";
	private static final String MSG_SMS_SENT_RESULT_ERROR_RADIO_OFF = "SMS Radio off while sending to: %s";
	
	private static final long[] VIBRATION = new long[] { 100, 150, 100, 150 };
	
	public int notificationId;
	public String phoneNumber;
	public String message;
	public ProgressBar progressBar;
	public int icon;

	/**
	 * Constructor.
	 * 
	 * @param notificationId
	 * @param phoneNumber
	 * @param message
	 * @param progressBar
	 */
	public SMSSentBroadcastReciever(int notificationId, int icon, String phoneNumber, String message, ProgressBar progressBar) {
		super();
		this.notificationId = notificationId;
		this.icon = icon;
		this.phoneNumber = phoneNumber;
		this.message = message;
		this.progressBar = progressBar;
	}

	/* (non-Javadoc)
	 * @see android.content.BroadcastReceiver#onReceive(android.content.Context, android.content.Intent)
	 */
	@Override
	public void onReceive(Context context, Intent intent) {

		String msg = null;

		switch (getResultCode()) {
		case Activity.RESULT_OK:
			msg = MSG_SMS_SENT_OK;
			break;
		case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
			msg = MSG_SMS_SENT_RESULT_ERROR_GENERIC_FAILURE;
			break;
		case SmsManager.RESULT_ERROR_NO_SERVICE:
			msg = MSG_SMS_SENT_RESULT_ERROR_NO_SERVICE;
			break;
		case SmsManager.RESULT_ERROR_NULL_PDU:
			msg = MSG_SMS_SENT_RESULT_ERROR_NULL_PDU;
			break;
		case SmsManager.RESULT_ERROR_RADIO_OFF:
			msg = MSG_SMS_SENT_RESULT_ERROR_RADIO_OFF;
			break;
		}

		// Do we have a progress bar? If true then hide it.
		if( progressBar != null){
			progressBar.setVisibility(ProgressBar.INVISIBLE);
		}

		if (msg != null) {

			long when = System.currentTimeMillis();
			String notificationMsg = String.format(msg,
					new Object[] { phoneNumber, message });
			
			String sentMsg = String.format("The message was:\n%s ",
					new Object[] { message });
			
			NotificationHelper.sendNotification(context,
					notificationId, notificationMsg,
					Toast.LENGTH_SHORT, icon,
					notificationMsg, when,
					notificationMsg, sentMsg, VIBRATION);

		}
	}
}